﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DormMS.IService;
using SqlSugar;
using DormMS.Model.ViewModels;
using Infrastructure.Dao;
using DormMS.Model;
using DormMS.Model.Enum;

namespace DormMS.Service
{
    public class ShopService : IShopService
    {
        private ICarouselService carouselservice;
        public ShopService(ICarouselService _carouselservice)
        {
            carouselservice = _carouselservice;
        }


        public ShopIndexModel ShopIndex()
        {
            using (var Db = DbConfig.GetInstance())
            {
                var response = new ShopIndexModel();

                //一级分类
                response.FristCategoryList = Db.Queryable<Product_Category>().Where(m => m.Id > 0 && m.IsDisplay && m.ParentId == 0).OrderBy(" DisplayOrder Desc,Id Desc ").ToList();

                //轮播图
                response.CarouselList = carouselservice.GetCarousel((int)CarouselTypeEnum.首页);

                //头条
                response.HeadlineList = Db.Queryable<AdConfiguration>().Where(m => m.TypeId == (int)AdTypeEnum.头条).OrderBy(" Sort Desc,Id Desc ").ToList();

                //首页广告位
                response.AdList = Db.Queryable<AdConfiguration>().Where(m => m.TypeId == (int)AdTypeEnum.首页广告).OrderBy(" Sort Desc,Id Desc ").ToList();

                //限时抢购活动信息
                var begintime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                var endtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
                response.Spike = Db.Queryable<Activity_Spike>().Where(m => m.BeginTime >= begintime && m.BeginTime <= endtime).OrderBy(o => o.BeginTime).SingleOrDefault() ?? new Activity_Spike();

                //专题活动
                response.TopicList = Db.Queryable<Activity_SpecialTopic>().OrderBy(" Sort Desc,Id Desc ").Take(8).ToList() ?? new List<Activity_SpecialTopic>();

                //为你推荐
                response.RecommendProduct = Db.Queryable<Product>().Where(m => m.IsRecommend && m.IsDisplay).OrderBy(" Sort Desc,Id Desc ").Take(4).ToList();
                if (response.RecommendProduct != null && response.RecommendProduct.Count > 0)
                {
                    response.RecommendProduct.ForEach(m =>
                    {
                        var speclist = Db.Queryable<Product_Spec>().Where(w => w.ProductSku == m.Sku && w.IsDeleted == false && w.Stock - w.WaitSendStock > 0).ToList() ?? new List<Product_Spec>();
                                            if (speclist != null && speclist.Count > 0)
                        {
                            m.Price = speclist.Min(s => s.Price);
                            m.MarketPrice = speclist.Max(s => s.MarketPrice);
                        }
                        
                    });
                }

                return response;
            }
        }


    }
}
